package com.xstablet.activity;

import android.content.pm.ActivityInfo;
import android.os.Environment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.app.EventBusTagUtils;
import com.lib.bean.ConfigBean;
import com.lib.bean.Event;
import com.lib.bean.UpdateVersionBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.system.SystemUtil;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverListener;
import com.lib.observer.ObserverManager;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.utls.appupdate.AppDownloadManager;
import com.lib.utls.appupdate.AppUpdateDialog;
import com.xstablet.R;
import com.xstablet.fragment.MainStudentFragment;
import com.xstablet.fragment.MainTeacherFragment;
import com.xstablet.fragment.StudentNewShowFragment;
import com.xstablet.fragment.TabletResourceFragment;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import qqkj.qqkj_library.app.install.InstallUtil;
import qqkj.qqkj_library.app.version.VersionUtil;
import qqkj.qqkj_library.network.http.HttpDownloadUtil;
import tablet.module_tools.fragment.ToolsFragment;
import tablet.module_user.bean.BaseBean;
import tablet.module_user.fragment.StudentInfoRecordFragment;
import tablet.module_user.fragment.StudentInfoRecordFragment_1;
import tablet.module_user.fragment.StudentMenuFragment;
import tablet.module_user.fragment.StudentMenuFragment_1;
import tablet.module_user.fragment.UserInfoFragment;

@Route(path = ARouterPathUtils.Tablet_App_MainActivity)
public class MainActivity extends BaseAppActivity implements ObserverListener {

    ViewPager vpContent;

    List<Fragment> fgList;

    AppDownloadManager downloadManager;

    //套餐具体情况
    String package_content = "";

    private void chooseUpdateMethod() {

        showUpdateDialog();
    }

    @Override
    protected void onCreateView() {

        package_content = getIntent().getStringExtra("package_content");
        if (StringUtil.isNotEmpty(package_content, true)) {
            LogUtil.e("MainActivity中package_content的值为:" + package_content);
        } else {
            LogUtil.e("MainActivity中package_content的值为空");
        }

        vpContent = findViewById(R.id.vp_content);

        initViewPager();

        //更新检测，有更新，弹出更新提示框
        chooseUpdateMethod();

        ObserverManager.getInstance().add(this);

        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        bindYoumengTokenByUser();

        initPermission();

        requestConfig();

    }

    private void requestConfig() {


        HttpUtils.with(this)
                .addParam("requestType", "CONFIG")
                .execute(new HttpNormalCallBack<ConfigBean>() {
                    @Override
                    public void onSuccess(ConfigBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            SharedPreferenceManager.getInstance(MainActivity.this).getUserCache().setQiNiuToken(result.getObj().getToken());
                            SharedPreferenceManager.getInstance(MainActivity.this).getUserCache().setQiNiuUrl(result.getObj().getBaseurl());
                            SharedPreferenceManager.getInstance(MainActivity.this).getUserCache().setConfigJson(new Gson().toJson(result));

                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    private void initPermission() {

        PermissionUtil.getInstance(this).externalMain(new PermissionUtil.RequestPermission() {
            @Override
            public void onRequestPermissionSuccess() {

            }

            @Override
            public void onRequestPermissionFailure() {

            }

        });

    }


    @Override
    protected void onResume() {
        super.onResume();

        //设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ObserverManager.getInstance().remove(this);
    }

    private void showUpdateDialog() {

        HttpUtils.with(this)
                .addParam("requestType", "TABLET_VERSION")
                .addParam("version_type", "2")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UpdateVersionBean>() {
                    @Override
                    public void onSuccess(UpdateVersionBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            double localVersion = SystemUtil.getVersionCode(MainActivity.this);

                            double newVersion = 0;

                            if (StringUtil.isNotEmpty(result.getObj().getVersion(), true)) {
                                newVersion = Double.parseDouble(result.getObj().getVersion());

                                if (newVersion > localVersion) {
                                    initDialogUI(result);

//                                    downloadApk(result);

                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    public void downloadApk(UpdateVersionBean result) {
        //参数说明1:String(网络请求地址)
        //
        //参数说明2:String(下载文件存放的目录名称,例如存放到手机根目录下/aaa文件夹,则传aaa)
        //
        //参数说明3:String(下载后保存的文件名称, 例如 aaa.jpg,aaa.zip,aaa.xxxx)
        //
        //参数说明4:boolean(是否打开调试日志...设置为true 的时候 logcat中输入 qqkj_frame)
        //
        //参数说明5:HttpDownloadListener(下载进度回调监听,例如,返回10,就是10%)
        //
        //作者：陈二二二狗
        //链接：https://www.jianshu.com/p/357c0717fb1d
        //来源：简书
        //著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

        String savePath = Environment.getExternalStorageDirectory() + "/xstablet/apkfile/";
        HttpDownloadUtil.getIns().get_http_download(result.getObj().getDownload_url(),
                "xstablet", "xstablet" + result.getObj().getVersion_name() + ".apk",
                true, new HttpDownloadUtil.HttpDownloadListener() {
                    @Override
                    public void get_progress(int i) {

                        if (i == 100) {
                            InstallUtil.getIns(MainActivity.this)._get_install_apk("xstablet");
                        }
                    }
                });
    }


    private void initDialogUI(UpdateVersionBean result) {

//        String updateIntroduce = "";
//        if (result.getObj().getVersion_introduction() != null) {
//            for (int i = 0; i < result.getObj().getVersion_introduction().size(); i++) {
//                if (StringUtil.isNotEmpty(result.getObj().getVersion_introduction().get(i), true)) {
//                    updateIntroduce = updateIntroduce + result.getObj().getVersion_introduction().get(i) + "\n";
//                }
//            }
//        }
//
//        UpdateConfig updateConfig = new UpdateConfig();
//        updateConfig.setCheckWifi(true);
//        updateConfig.setNeedCheckMd5(true);
//        updateConfig.setApkSaveName("xuesitu.apk");
//        String apkDownloadPath = Environment.getExternalStorageDirectory() + "/xuesitu/apkPath/";
//        updateConfig.setApkSavePath(apkDownloadPath);
//        updateConfig.setAlwaysShow(true);
//        updateConfig.isShowNotification();
//        updateConfig.setShowDownloadingToast(true);
//
//        UiConfig uiConfig = new UiConfig();
//        uiConfig.setUiType(UiType.CUSTOM);
//        uiConfig.setCustomLayoutId(R.layout.dialog_app_update);
//
//        UpdateAppUtils
//                .getInstance()
//                .apkUrl(result.getObj().getDownload_url())
//                .updateTitle("发现新版本" + result.getObj().getVersion_name())
//                .updateContent(updateIntroduce)
//                .updateConfig(updateConfig)
//                .uiConfig(uiConfig)
//                .setOnInitUiListener(new OnInitUiListener() {
//                    @Override
//                    public void onInitUpdateUi(@Nullable View view, @NotNull UpdateConfig updateConfig, @NotNull UiConfig uiConfig) {
//
//                    }
//                })
//                .update();

        AppUpdateDialog dialog = new AppUpdateDialog(this);
        dialog.setAppUpdateInfo(result);

        downloadManager = new AppDownloadManager(MainActivity.this);

        if (downloadManager != null) {
            downloadManager.resume();
        }

        dialog.setOnUpdateClickListener(new AppUpdateDialog.OnUpdateClickListener() {
            @Override
            public void update(final AppUpdateDialog updateDialog) {
                String title = "版本" + result.getObj().getVersion_name();
                String desc = "新版来啦";

                downloadManager.setUpdateListener(new AppDownloadManager.OnUpdateListener() {
                    @Override
                    public void update(int currentByte, int totalByte) {

                        LogUtil.e("------------------------当前的大小为：" + currentByte);
                        LogUtil.e("------------------------总的大小为：" + totalByte);

                    }
                });
                downloadManager.downloadApk(result.getObj().getDownload_url(), title, desc);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.show();

    }

    /**
     * 初始化ViewPager，方便后期与tabLayout关联
     */
    private void initViewPager() {
        if (fgList == null)
            fgList = new ArrayList<>();

        int platform_teacher = SharedPreferenceManager.getInstance(this).getUserCache().getPlatform_teacher();
//        if (0 == platform_teacher) {
//            fgList.add(new MainStudentFragment(package_content));
//            fgList.add(new StudentNewShowFragment());
//            fgList.add(new StudentMenuFragment());
//            fgList.add(new StudentInfoRecordFragment());
//        } else {
//            fgList.add(new MainTeacherFragment());
//            fgList.add(new UserInfoFragment());
//        }

        if (0 == platform_teacher) {
            fgList.add(new StudentNewShowFragment(package_content));
            fgList.add(new TabletResourceFragment());
            fgList.add(new StudentMenuFragment_1());
            fgList.add(new StudentInfoRecordFragment_1());
        } else {
            fgList.add(new MainTeacherFragment());
            fgList.add(new UserInfoFragment());
        }


        fgList.add(new ToolsFragment());

//        //2020-11-27 测试外部跳转
//        fgList.add(new MainStudentFragment(""));
//        fgList.add(new ToolsFragment());

        ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fgList);
        vpContent.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();
    }

    /**
     * ViewPager的适配器。
     */
    class ViewPagerAdapter extends FragmentPagerAdapter {

        List<Fragment> fragmentList;

        public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "";
        }
    }


    @Override
    public void observerUpData(String content) {

        if (StringUtil.isNotEmpty(content, true)) {
            if ("relogin".equals(content)) {
                ARouter.getInstance().build(ARouterPathUtils.Tablet_User_LoginActivity).navigation();
            }
        }
    }

    /**
     * 登录后需要绑定
     * 每次进入页面如何用户Token和友盟Token都不为空那么再次绑定
     */
    private void bindYoumengTokenByUser() {
        String userToken = SharedPreferenceManager.getInstance(this).getUserCache().getUserToken();
        String youMengToken = SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken();
        if (!userToken.equals("") && !youMengToken.equals("")) {
            bindYouMengToken();
        }
    }

    private void bindYouMengToken() {

        if (StringUtil.isNotEmpty(SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken(), true)) {
            LogUtil.e("@@@@@@@@@@@@@@@@@@@@@@@" + SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken());
            HttpUtils.with(this)
                    .addParam("requestType", "SET_APPID")
                    .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                    .addParam("app_id", SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken())
                    .addParam("client", "XSTTablet")
                    .execute(new HttpNormalCallBack<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean result) {

                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }
    }

    /**
     * 全局登录监听
     *
     * @param event
     */
    @Subscriber(tag = EventBusTagUtils.HttpCallBack)
    public void fromHttpCallBack(Event event) {
        switch (event.getEventCode()) {
            case 1: {

                ARouter.getInstance().build(ARouterPathUtils.Tablet_User_LoginActivity).navigation();

                break;
            }
        }
    }
}
